package com.javaee.xiangyang.controller.Admin;

import com.javaee.xiangyang.common.ServiceResultEnum;
import com.javaee.xiangyang.entity.Admin;
import com.javaee.xiangyang.service.AccountService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/Admin")
public class AccountController {

    @Resource
    AccountService accountService;

    @GetMapping("/ToLogin")
    public ModelAndView togo(ModelAndView modelAndView) {
        modelAndView.setViewName("admin/login");
        return modelAndView;
    }

    /**
     * 管理员登录
     * 成功构造Session
     * 失败返回失败原因
     * 参数:
     * adminAccount:账号
     * adminPassword:密码
     */
    @RequestMapping("/Login")
    public ModelAndView adminLogin(ModelAndView modelAndView, HttpSession session, Admin admin) {
        ServiceResultEnum serviceResultEnum = accountService.adminLogin(admin);
        if (serviceResultEnum == ServiceResultEnum.SUCCESS) {
            //登录成功   记录Session
            session.setAttribute("Admin", admin);
            modelAndView.setViewName("admin/index");
            return modelAndView;
        }
        modelAndView.addObject("ERROR", serviceResultEnum.getResult());
        modelAndView.setViewName("admin/login");
        return modelAndView;
    }

    /**
     * 管理员修改密码
     * 成功返回
     * 参数:
     * adminAccount:账号
     * adminPassword:密码
     */
    @RequestMapping("/UpdateAdmin")
    public ModelAndView updateAdmin(ModelAndView modelAndView, Admin admin) {
        accountService.adminUpdatePassword(admin);
        modelAndView.setViewName("redirect:/Admin/loginOut");
        return modelAndView;
    }

    /**
     * 管理员退出登录
     */
    @RequestMapping("/loginOut")
    public ModelAndView loginOut(HttpSession session, ModelAndView modelAndView) {
        session.removeAttribute("Admin");
        modelAndView.setViewName("redirect:/Admin/ToLogin");
        return modelAndView;
    }
}
